
var FormData = require( 'form-data' );
var fs = require( 'fs' );
const fetch = require( 'node-fetch' )
module.exports = class extends think.global.service {
  async indexAction () {
    var postData = this.post()
    console.log('====================================')
    console.log('接收参数', postData)
    if (!this.file('image')) {
      try {
        console.log('发送请求')
        var result = await think.http.post(this.$url, this.post(), this.$config)
        this.model('user').clearTimeoutList(this.post().openid)
        this.json(result.data)
        console.log('请求返回')
      } catch (e){
        this.ctx.fail(1000, e.message)
      }
      return
    }
    var formData = new FormData()
    for ( var i in postData ) {
      formData.append( i, postData[i] )
    }
    formData.append( 'image', fs.createReadStream( this.file( 'image' ).path ) )
    formData.append( 'client', 'news' )
    try {
      var result
      await fetch( this.$url, { method: 'POST', body: formData } ).then( function( res ) {
        return res.json()
      } ).then( function( json ) {
        result = json
      } );
      this.model('user').clearTimeoutList(this.post().openid)
      console.log('清除超时离线回复', this.post().openid)
      this.json( result )
    } catch ( e ) {
      this.ctx.fail( 1001, e.message )
    }



    // try {
    //   this.post().image = files
    //   var result = await think.http.post(this.$url, postData, this.$config)
    // } catch (e){
    //   this.ctx.fail(1000, e.message)
    // }
    // console.log(result)
    // this.json(result)
  }
};
// {
//   "appid":"wx283f05dbb353b933",
//   "openid":"oo5pZ0-cIg9kiDc3H0HCV9ShrXAo",
//   "image":1,
//   "cs_id":100,
//   "send_type":1002,
//   "send_time":1539225384,
//   "type":"text"
// }